package dper.study.codes.concurrent.model;

import org.apache.log4j.Logger;

import java.util.LinkedList;

/**
 * Created by leichen on 2017/3/20.
 * simple implement Producer-Consumer Model
 */
public class ProConBufferWaitNotifyAll implements ProConBuffer{
    Logger logger = Logger.getLogger(ProConBufferWaitNotifyAll.class) ;

    private int bufferLen = 10 ;

    private LinkedList<Integer>  buffer = new LinkedList<Integer>() ;

    public synchronized void set(int i){
        while (buffer.size()==bufferLen) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        buffer.add(i) ;
        logger.info(Thread.currentThread()+"\tproducer add "+i+" in buffer\tNow size " + buffer.size());
        notifyAll();
    }
    public synchronized int get(){
        while(buffer.size()==0){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        int head =  buffer.poll() ;
        logger.info(Thread.currentThread()+"\tconsumer consume "+ head+" from buffer\tNow size " + buffer.size() );
        notifyAll();
        return head ;
    }
}
